package com.baizhi.service.impl;

import com.baizhi.aspect.LogAnnotation;
import com.baizhi.entity.Menu;
import com.baizhi.mapper.MenuMapper;
import com.baizhi.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author haiyu
 * @since 2021-09-06
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Resource
    private MenuMapper mm;
    @Override
    public List<Menu> selectUserMenu() {
        List<Menu> menus = baseMapper.selectUserMenu();
        return menus;
    }
    @Override
    //@LogAnnotation //表示这个方法要添加额外功能
    public List<Menu> selectMenuTree() {

        List<Menu> menus = baseMapper.selectList(null);//查询出所有的菜单
        //想办法从menus获取到一级菜单，再给一级菜单children属性赋值
        List<Menu> collect = menus.stream().filter((menu) -> {
            return menu.getParentId() == 0;
        }).peek((menu) -> {
            //想办法获取到每个menu的子菜单
            menu.setChildren(getChildren(menu.getMenuId(), menus));
        }).collect(Collectors.toList());
        return collect;
        // collect.forEach(System.out::println);
    }

    @Override
    public List<Menu> selectPermissionByUsername(String username) {
        List<Menu> menus = mm.selectPermissionByUsername(username);
        return menus;
    }

    //        根据传来的id值,这个id是父菜单的id,来找该id下面的所有子菜单的集合
    private List<Menu> getChildren(Long parentId,List<Menu> menus){
        return  menus.stream().filter((menu) -> {
            return menu.getParentId() == parentId;
        }).peek((menu)->{menu.setChildren(getChildren(menu.getMenuId(),menus));}).collect(Collectors.toList());

    }
}
